#include <asl_core.h>
#include <asl_executor.h>
#include <asl_executor_exp.h>
#include <asl_executor_include.h>

extern executor_info_t global_executor;

/**
 *
 * @param is
 * @param var_table
 * @return
 */
executor_control_t *executor_run_include(include_statement_t *is, hash_t *var_table) {
    value_t *v, *tv;
    char *filename;
    FILE *input;
    statement_list_t *sl;
    v = executor_exp_run(is->e, var_table);
    tv = value_transfer_string(v);
    filename = util_get_realpath(tv->u.str.val);
    if (is_empty(filename)) {
        exception_fatal_exc("Included file %s is not exist", tv->u.str.val);
    }
    /**
     * find statement list
     */
    sl = (statement_list_t *) hash_find(global_executor.statement_table, filename, strlen(filename));
    if (is_empty(sl)) {
        input = fopen(filename, "r");
        if (is_empty(input)) {
            exception_fatal_exc("Included file %s is cannot open", tv->u.str.val);
        }
        compiler_load_input(filename, input);
        global_compiler.statement_list = compiler_create_statement_list();
        compiler_run();
        compiler_unload_input();
        hash_insert_or_update(global_executor.statement_table, filename,
                              strlen(filename), (void *) global_compiler.statement_list);
        sl = global_compiler.statement_list;
    }
    return executor_run_statement(sl, var_table);
}